package videoCapture;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;

import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.TargetDataLine;

public class AudioP2P1 implements Runnable{
	public static final int PORT = 5000;
	private DatagramSocket dataSocket;
	private DatagramPacket dataPacket;
	private byte sendByte[];
	private static int BUFSIZE = 1024;
	private byte[] IP = { (byte) 127, (byte) 0, (byte) 0, (byte) 1 };

	public AudioP2P1() throws SocketException {
		super();
		dataSocket = new DatagramSocket(PORT);
		sendByte = new byte[BUFSIZE];
		dataPacket = new DatagramPacket(sendByte, BUFSIZE);
	}

	public byte[] getIP() {
		return IP;
	}

	public void setIP(byte[] iP) {
		IP = iP;
	}

	public void start() throws Exception {
		final AudioFormat format = getFormat();
		DataLine.Info info = new DataLine.Info(TargetDataLine.class, format);
		final TargetDataLine line = (TargetDataLine) AudioSystem.getLine(info);
		line.open(format);
		line.start();
		int bufferSize = (int) format.getSampleRate() * format.getFrameSize();
		byte buffer[] = new byte[bufferSize];
		// ByteArrayOutputStream out = new ByteArrayOutputStream();
		while (true) {
			int count = line.read(buffer, 0, bufferSize);
			if (count > 0) {
				// out.write(buffer, 0, count);
				send(buffer);
			}
		}
		// out.close();
	}

	public void send(byte[] buffer) throws IOException {
		int index = 0;
		int dataSize = 0;
		while (index < buffer.length) {
			int i;
			for (i = 0; i < BUFSIZE && (index + i) < buffer.length; i++) {
				// System.out.println("client "+i);
				sendByte[i] = buffer[index + i];
			}
			index += i;
			dataSize += i;
			dataPacket = new DatagramPacket(sendByte, i,
					InetAddress.getByAddress(IP), AudioP2P2.PORT);
			dataSocket.send(dataPacket);
		}
//		 System.out.println("Audio dataSize " + dataSize);
		dataSocket.send(new DatagramPacket(new byte[0], 0, InetAddress
				.getByAddress(IP), AudioP2P2.PORT));
	}

	private AudioFormat getFormat() {
		float sampleRate = 16000;
		int sampleSizeInBits = 8;
		int channels = 1;
		boolean signed = true;
		boolean bigEndian = true;
		return new AudioFormat(sampleRate, sampleSizeInBits, channels, signed,
				bigEndian);
	}
	

	@Override
	public void run() {
		// TODO Auto-generated method stub
		try {
			this.start();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public static void main(String[] args) throws Exception {
		AudioP2P1 p1 = new AudioP2P1();
		if (args.length != 0) {
			String[] st = args[0].split("\\.");

			byte[] tb = { (byte) Integer.parseInt(st[0]),
					(byte) Integer.parseInt(st[1]), (byte) Integer.parseInt(st[2]),
					(byte) Integer.parseInt(st[3]) };
		
		}
//		p1.start();
		Thread thread = new Thread(p1);
		thread.start();
	}

}
